package com.tenglong.teacher.ui.homework;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.google.gson.Gson;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.attachment.FileAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.HomeDetailInfo;
import com.tenglong.teacher.data.resultInfo.HomeWorkIM;
import com.tenglong.teacher.data.resultInfo.HomeworkDetailInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.answerq.P2PRecord;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.homepage.FullyGridLayoutManager;
import com.tenglong.teacher.ui.publish.HomeworkCorrectingActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.tenglong.teacher.ui.homework.HomeWorkDetailAdapter.GRIDSPAN_IMAGE;


public class HomeWorkDetailActivity extends BaseActivity implements View.OnClickListener, OnRefreshListener {

    private RecyclerView recyclerView;
    private HomeWorkDetailAdapter adapter;
    private GridLayoutManager gridLayoutManager;
    private String sessionId;
    private String title;
    private String accid;
    private TextView mSubmit;
    private int mStatus;
    private List<IMMessage> filterMsgs;
    private List<IMMessage> sortedMsgs;
    private List<IMMessage> newsMsgs;
    private SmartRefreshLayout smartRefreshLayout;
    private boolean isFirst = true;
    private Intent returnIntent = new Intent();
    private P2PRecord record;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homeworkdetail);
        recyclerView = findViewById(R.id.list);
        mSubmit = findViewById(R.id.submit);
        smartRefreshLayout = findViewById(R.id.smartRefreshLayout);
        ClassicsHeader headerView = new ClassicsHeader(this);
        ClassicsFooter footView = new ClassicsFooter(this);
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        smartRefreshLayout.setRefreshHeader(headerView);
        smartRefreshLayout.setRefreshFooter(footView);
        smartRefreshLayout.setEnableLoadMore(false);
        smartRefreshLayout.setOnRefreshListener(this);

        mSubmit.setOnClickListener(this);
        gridLayoutManager = new FullyGridLayoutManager(this, GRIDSPAN_IMAGE);
        adapter = new HomeWorkDetailAdapter();
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(new GridMarginDecoration(this, adapter));
        recyclerView.setAdapter(adapter);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.getSpanSize(position);
            }
        });
        sessionId = getIntent().getStringExtra("sessionid");
        title = getIntent().getStringExtra("title");
        accid = getIntent().getStringExtra("accid");
        record = new P2PRecord();
//        mStatus = getIntent().getIntExtra("status", HW_STATUS_CREATE);
//        if (mStatus == HW_STATUS_FINISH_CONFIRMED_BY_TEACHER) {
//            mSubmit.setText("完成作业");
//        } else if (mStatus == HW_STATUS_FINISH) {
//            mSubmit.setVisibility(View.GONE);
//        } else {
//            mSubmit.setText("提交作业");
//        }
        setTitle(title);
        requestData();
    }

    private void requestData() {
        if (isFirst) {
            isFirst = false;
            showProgressDialog("数据获取中...");
        }
        CreateRequestEntity.getWebService().getHomeworkMsgBySessionId(sessionId).enqueue(new Callback<BaseResult<HomeworkDetailInfo>>() {

            @Override
            public void onResponse(Call<BaseResult<HomeworkDetailInfo>> call, Response<BaseResult<HomeworkDetailInfo>> response) {
                smartRefreshLayout.finishRefresh(true);
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    mStatus = response.body().data.statu;
                    returnIntent.putExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, mStatus);
                    setResult(Activity.RESULT_OK, returnIntent);
                    List<HomeWorkIM> nim = response.body().data.list;
                    if (nim != null && nim.size() > 0) {
                        for (HomeWorkIM homeWorkIM : nim) {
                            homeWorkIM.setP2PRecord(record);
                        }
                        for (HomeWorkIM homeWorkIM : nim) {
                            homeWorkIM.getDirect();
                        }
//                        for (HomeWorkIM homeWorkIM : nim) {
//                            Log.e("参数", "方向1" + direct.name());
//                            sortMessage(homeWorkIM);
//                        }
//                        Log.e("参数", new Gson().toJson(detailInfos));
                        List<IMMessage> tempItems = new ArrayList<>();
                        tempItems.addAll(nim);
                        onLoadMessages(tempItems);
                    } else {
                        ToastUtils.showCenterToast("服务器异常");
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<HomeworkDetailInfo>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
                smartRefreshLayout.finishRefresh(false);
            }
        });
    }

    private void onLoadMessages(List<IMMessage> messages) {
        filterMsgs = messages;
        sortedMsgs = sortMessages(messages);
        adapter.clear();
        adapter.addAll(sortedMsgs);
        adapter.notifyDataSetChanged();
    }


//    private MsgDirectionEnum direct = MsgDirectionEnum.Out;
//    private HomeDetailInfo info;
//    private List<HomeDetailInfo> detailInfos = new ArrayList<>();
//    public void sortMessage(IMMessage message) {
//        if (direct != message.getDirect()) {
//            info = new HomeDetailInfo();
//            detailInfos.add(info);
//            info.direct = message.getDirect();
//        } else {
//            if (info == null) {
//                info = new HomeDetailInfo();
//                detailInfos.add(info);
//                info.direct = direct;
//            }
//        }
//        direct = info.direct;
//        if (message.getMsgType() == MsgTypeEnum.text) {
//            String text = message.getContent();
//            if (!TextUtils.isEmpty(text)) {
//                if (text.contains("错题原因：") || text.contains("作业点评：") || text.contains("书写评分：") || text.contains("老师批语：")
//                        || text.contains("错题原因:") || text.contains("作业点评:") || text.contains("书写评分:") || text.contains("老师批语:")) {
//                    if (text.contains("错题原因：") || text.contains("错题原因:") || text.contains("&/")) {
//                        info.errorContents.add(text);
//                    } else {
//                        info.evaluate = text;
//                    }
//                } else {
//                    info.answer = text;
//                }
//            }
//        } else if (message.getMsgType() == MsgTypeEnum.audio) {
//            info.audioUrl = getImageUrl(message);
//        } else if (message.getMsgType() == MsgTypeEnum.image) {
//            info.imageUrls.add(getImageUrl(message));
//        }
//    }
//
//
//    private String getImageUrl(IMMessage imMessage) {
//        FileAttachment msgAttachment = (FileAttachment) imMessage.getAttachment();
//        String path = msgAttachment.getPath();
//        String thumbPath = msgAttachment.getThumbPath();
//        String url = msgAttachment.getUrl();
//        if (!TextUtils.isEmpty(thumbPath)) {
//            return thumbPath;
//        } else if (!TextUtils.isEmpty(path)) {
//            return path;
//        } else if (!TextUtils.isEmpty(url)) {
//            return url;
//        } else {
//            return "";
//        }
//    }


    private List<IMMessage> sortMessages(List<IMMessage> messages) {
        List<String> title = new ArrayList<>();
        title.add("学生作业");
        title.add("批改作业");
        List<IMMessage> newMsgs = new ArrayList<>();
        IMMessage msg = MessageBuilder.createCustomMessage(accid, SessionTypeEnum.P2P, new HWTitle("作业内容", 2));
        newMsgs.add(msg);
        MsgDirectionEnum status = messages.get(0).getDirect();
        int indicator = 0;
        int txtpos = 1;
        int picpos = 1;
        int audiopos = 1;
        int piccount = 0;
        int picImgType = 0;
        for (int i = 0; i < messages.size(); i++) {
            if (status != messages.get(i).getDirect()) {
                newMsgs.add(MessageBuilder.createCustomMessage(accid, SessionTypeEnum.P2P, new HWTitle(title.get(indicator), indicator)));
                txtpos = newMsgs.size();
                picpos = newMsgs.size();
                audiopos = newMsgs.size();
                piccount = 0;
                if (i == 0 || !messages.get(i - 1).getFromAccount().equals(messages.get(i).getFromAccount())) {
                    picImgType++;
                }
                if (messages.get(i).getMsgType() == MsgTypeEnum.text) {
                    newMsgs.add(txtpos, messages.get(i));
                    txtpos = txtpos + 1;
                    picpos = picpos + 1;
                    audiopos = audiopos + 1;
                } else if (messages.get(i).getMsgType() == MsgTypeEnum.audio) {
                    newMsgs.add(audiopos, messages.get(i));
                    picpos = picpos + 1;
                    audiopos = audiopos + 1;
                } else if (messages.get(i).getMsgType() == MsgTypeEnum.image) {
                    messages.get(i).setPushContent(String.valueOf(piccount));
                    piccount++;
                    newMsgs.add(picpos, messages.get(i));
                    picpos = picpos + 1;
                    ((HomeWorkIM) messages.get(i)).setType(picImgType);
                }
                status = messages.get(i).getDirect();
                indicator = (indicator + 1) % 2;
            } else {
                if (i == 0 || !messages.get(i - 1).getFromAccount().equals(messages.get(i).getFromAccount())) {
                    picImgType++;
                }
                if (messages.get(i).getMsgType() == MsgTypeEnum.text) {
                    newMsgs.add(txtpos, messages.get(i));
                    txtpos = txtpos + 1;
                    picpos = picpos + 1;
                    audiopos = audiopos + 1;
                } else if (messages.get(i).getMsgType() == MsgTypeEnum.audio) {
                    newMsgs.add(audiopos, messages.get(i));
                    audiopos = audiopos + 1;
                } else if (messages.get(i).getMsgType() == MsgTypeEnum.image) {
                    messages.get(i).setPushContent(String.valueOf(piccount));
                    piccount++;
                    newMsgs.add(picpos, messages.get(i));
                    picpos = picpos + 1;
                    audiopos = audiopos + 1;
                    ((HomeWorkIM) messages.get(i)).setType(picImgType);
                }
            }
        }

        newsMsgs = new ArrayList<>();
        for (IMMessage message : newMsgs) {
            if (message instanceof HomeWorkIM) {
                if (((HomeWorkIM) message).getType() == picImgType && message.getMsgType() == MsgTypeEnum.image && message.getDirect() == MsgDirectionEnum.In) {
                    newsMsgs.add(message);
                }
            }
        }
        mSubmit.setVisibility((mStatus == 1 || mStatus == 5) && newsMsgs.size() > 0 ? View.VISIBLE : View.GONE);
        return newMsgs;
    }

    private void pigai() {
        if (newsMsgs.size() == 0) return;
        Intent intent = new Intent(this, HomeworkCorrectingActivity.class);
        intent.putExtra(HomeworkCorrectingActivity.KEY_HOME_IM_PARAMS, (Serializable) newsMsgs);
        intent.putExtra(HomeworkCorrectingActivity.KEY_ACCOUNT_ID, accid);
        intent.putExtra(HomeworkCorrectingActivity.KEY_SESSION_ID, sessionId);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_HOMEWORK_CORRECTING_ACTIVITY);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.submit:
                pigai();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_HOMEWORK_CORRECTING_ACTIVITY:
                    int state = data.getIntExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, 0);
                    if (state != 0) {
                        returnIntent.putExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, state);
                    }
                    setResult(Activity.RESULT_OK, returnIntent);
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }
}





